Ext.define('Seq.grid.Filter', {
    extend: "Ext.form.field.Text",
    xtype: "xgridfilter",

    maxLength: 40,
    width: 210,
    emptyText: '输入过滤条件',
    enableKeyEvents: true,

    triggers: {
        clear: {
            cls: 'x-form-clear-trigger',
            handler: function (cmp, trigger, e) {
                cmp.setValue('');
                cmp.clear();
            },
            hidden: true,
            scope: this
        },
        search: {
            cls: 'x-form-search-trigger x-fa fa-action',
            weight: 1,
            handler: function (cmp, trigger, e) {
                cmp.search();
            },
            scope: this
        }
    },

    listeners: {
        keydown(me, e, eOpts) {
            if (e.ENTER == e.getKey()) {
                me.search(me, me.getTrigger('search'), e);
            }
        }
    },

    getGrid: function () {
        var me = this, panel = me.up('panel');
        return panel.isXType('grid') ? panel : panel.down('grid');
    },

    clear: function () {
        var me = this;
        me.getGrid().getStore().removeFilter('stringfilter');
        me.getTrigger('clear').hide();
    },

    storeFilter: function (store, text) {
        var me = this, grid = me.getGrid(), fields = [], columns = grid.getColumns(), field;
        var values = text.split(' ');
        for (var i in columns) {
            field = columns[i].dataIndex;
            field && fields.push(field);
        }
        var stringFilter = new Ext.util.Filter({
            id: 'stringfilter',
            filterFn: function (item) {
                var datas = item.data;
                for (var i in fields) {
                    var data = datas[fields[i]];
                    if (!Ext.isEmpty(data)) {
                        if (Ext.isObject(data) && me.contains(data.name, values)) {
                            return true;
                        } else if (data.toString && me.contains(data.toString(), values)) {
                            return true;
                        }
                    }
                }
                return false;
            }
        });
        store.addFilter(stringFilter);
    },

    contains: function (data, values) {
        for (var i in values) {
            if (-1 == data.indexOf(values[i])) {
                return false;
            }
        }
        return true;
    },

    search: function () {
        var me = this, text = me.getValue();
        if (Ext.isEmpty(text)) {
            me.clear();
        } else {
            me.getTrigger('clear').show();
            me.storeFilter(me.getGrid().getStore(), text);
        }
    }

});